package array;

import java.util.ArrayList;
import java.util.List;

public class leetcode54 {
    public static void main(String[] args) {
//        int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
        int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
//        int[][] matrix = {{1,2,3,4}};
        List<Integer> results = spiralOrder(matrix);
        for (int i = 0; i < results.size(); i++) {
            System.out.print(results.get(i) + " ");
        }
    }

    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> results = new ArrayList<>();
        if (matrix == null || matrix.length == 0) return results;

        int m = matrix.length;//记录矩阵的行数
        int n = matrix[0].length;//记录矩阵的列数
        int top = 0; //每一圈的顶行
        int bottom = m - 1; // 没一圈的底行
        int left = 0; //每一圈的左列
        int right = n-1; //每一圈的右列
        while(top <= bottom && left <= right){
            for(int i = left; i <= right; i++){
                results.add(matrix[top][i]);
            }
            top++;
            for(int i = top; i <= bottom; i++){
                results.add(matrix[i][right]);
            }
            right--;

            if(top <= bottom) {//检查是否还有行未打印
                for (int i = right; i >= left; i--) {
                    results.add(matrix[bottom][i]);
                }
                bottom--;
            }
            if(left <= right){
                for (int i = bottom; i >= top; i--) {
                    results.add(matrix[i][left]);
                }
                left++;
            }
        }

        return results;
    }
}
